package com.java110.mall.user.cmd.wechat;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.log.LoggerFactory;
import com.java110.dto.smallWeChat.SmallWeChatDto;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.ResponseConstant;
import com.java110.utils.constant.WechatConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;

@Java110Cmd(serviceCode = "wechat.wechatRefreshOpenId")
public class WechatRefreshOpenIdCmd extends Cmd {

    private final static Logger logger = LoggerFactory.getLogger(WechatRefreshOpenIdCmd.class);


    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {

        Assert.hasKeyAndValue(reqJson, "redirectUrl", "未包含跳转url");
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        String appId = MappingCache.getValue(WechatConstant.MALL_WECHAT_DOMAIN, "wechatAppId");
        String appSecret = MappingCache.getValue(WechatConstant.MALL_WECHAT_DOMAIN, "wechatAppSecret");


        String redirectUrl = reqJson.getString("redirectUrl");

        //分配urlCode
        String urlCode = UUID.randomUUID().toString();
        JSONObject param = new JSONObject();
        if (!redirectUrl.contains("appId")) {
            if (redirectUrl.indexOf("?") > 0) {
                redirectUrl += ("&appId=" + appId);
            } else {
                redirectUrl += ("?appId=" + appSecret);
            }
        }
        param.put("redirectUrl", redirectUrl);
        param.put("wAppId", reqJson.getString("wAppId"));
        CommonCache.setValue(urlCode, param.toJSONString(), CommonCache.defaultExpireTime);

        URL url = null;
        String openUrl = "";
        try {
            url = new URL(redirectUrl);

            String newUrl = url.getProtocol() + "://" + url.getHost();
            if (url.getPort() > 0) {
                newUrl += (":" + url.getPort());
            }

            openUrl = WechatConstant.OPEN_AUTH
                    .replace("APPID",appId)
                    .replace("SCOPE", "snsapi_base")
                    .replace(
                            "REDIRECT_URL",
                            URLEncoder
                                    .encode(
                                            (newUrl
                                                    + "/mall/api/wechat.wechatNotifyOpenId/992021051843980190/back?urlCode=" +
                                                    urlCode),
                                            "UTF-8")).replace("STATE", "1");

        } catch (Exception e) {
            logger.error("微信公众号鉴权 redirectUrl 错误 " + redirectUrl, e);
            throw new CmdException(ResponseConstant.RESULT_CODE_ERROR, e.getLocalizedMessage());
        }
        JSONObject urlObj = new JSONObject();
        urlObj.put("openUrl", openUrl);

        context.setResponseEntity(ResultVo.createResponseEntity(ResultVo.CODE_MACHINE_OK, ResultVo.MSG_OK, urlObj));

    }
}
